//
//  HJPicSelectViewController.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/10/7.
//  Copyright © 2016年 夏航军. All rights reserved.
//

/*
  1.设置视图显示模式
 */



import UIKit

private let reuseIdentifier = "Cell"


let selectCellMargin: CGFloat = 4
let colCount = 3

private let maxImageCount = 5
let itemW = (KScreenW - (CGFloat(colCount) + 1) * selectCellMargin) / CGFloat(colCount)

class HJPicSelectViewController: UICollectionViewController {

    //定义全局数据用于存储图片
    lazy var images: [UIImage] = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()

            self.collectionView!.register(HJPicSelectCell.self, forCellWithReuseIdentifier: reuseIdentifier)

               
    }



    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let imageCount = images.count
        //返回并限制最大图片数量
        return imageCount + (imageCount == maxImageCount ? 0 : 1)
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HJPicSelectCell
        
        cell.delegate = self
    
        if images.count == indexPath.item {
            //多出来的的Cell
            cell.image = nil
        }else {
            cell.image = images[indexPath.item]
        }
    
        return cell
    }

}


//实现UIImagePickerController的代理方法
extension  HJPicSelectViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        print(info)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //调用分类方法进行截图
        images.append(image.scaleImage(width: 600))
        
        //刷新collectionView
        self.collectionView?.reloadData()
        dismiss(animated: true, completion: nil)
        
    }
}






//在分类中实现代理方法
extension HJPicSelectViewController : HJPicSelectCellDelegate{
    
    func userWillAddPic() {
        
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        present(picker, animated: true, completion: nil)
        
    }
    
    func userWillRemovePic(cell: HJPicSelectCell) {
        
        //获取点击Cell的indexPath
        let indexpath = collectionView?.indexPath(for: cell)
        self.images.remove(at: indexpath!.item)
        
        //当图片为0 的时候,隐藏view
        self.view.isHidden = self.images.count == 0
        
        //刷新数据
        self.collectionView?.reloadData()
    }
}



//声明协议方法
@objc protocol HJPicSelectCellDelegate : NSObjectProtocol {
    //用户将要添加图片
      @objc optional func userWillAddPic()
    //用户将要删除图片
    @objc optional func userWillRemovePic(cell: HJPicSelectCell)
}




//Mark :自定义Cell
class  HJPicSelectCell : UICollectionViewCell {
    
    
    var image : UIImage? {
        didSet {
            addBtn.setImage(image, for: .normal)
            //设置删除按钮的隐藏于显示
            removeBtn.isHidden = (image == nil)
            let backImage : UIImage? = (image == nil ? #imageLiteral(resourceName: "compose_pic_add") : nil)
            addBtn.setBackgroundImage(backImage, for: .normal)
        }
    }
    
    
    //声明代理对象
    weak var delegate : HJPicSelectCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            
            make.edges.equalTo(contentView)
        }
        
        removeBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(contentView)
        }
        
        //给按钮添加点击事件
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        
        removeBtn.addTarget(self, action: #selector(removeBtnDidClick), for: .touchUpInside)
    }
    
    //添加按钮点击事件
    func addBtnDidClick() {
        if image != nil {
            print("已经有图片了")
            return
        }
        delegate?.userWillAddPic?()
        
    }
    //删除按钮点击事件
    func removeBtnDidClick(){
        
        delegate?.userWillRemovePic?(cell: self)
    }
    
    lazy var addBtn : UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        //设置视图显示模式
        btn.imageView?.contentMode = .scaleAspectFill
        return btn
    }()
    
    lazy var removeBtn : UIButton = {
       let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()
    
}








